import { useState, useEffect } from 'react'
import { getDetaiHttp } from "@/api/detail/detailapi"
import { useSearchParams, useNavigate } from 'react-router-dom'
import { detailType } from '@/api/detail/index'
import { NavBar } from 'antd-mobile'

function Detail() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams();//用于获取路由传过来的数据
  const detailId = searchParams.get('id')//用于获取路由传过来的数据
  const [detail, setDetail] = useState<detailType | null>(null)
  useEffect(() => {
    console.log(detailId)
    handleGetDetaiHttp()
  }, [])

  const handleGetDetaiHttp = async () => {
    const res = await getDetaiHttp(detailId!)//detailId!,由于ts会认为detailId不仅会是一个字符串，还有可能是个null，加！的意思是非空断言，向ts保证detailId一定会有值，不会是个null
    console.log(res.data)
    setDetail(res.data)
  }

  const back = () => {
    navigate(-1)
  }

  // 当detail还未加载过来时，下面的__html会出现ts报错，所以加上此代码，在detail还未加载过来的时候就先显示Loading的div标签，加载完成再显示详情页面
  if (!detail) {
    return <div>Loading.....</div>
  }

  return (
    <div>
      <NavBar onBack={back}>{detail?.title}</NavBar>

      {/* div标签上加上 dangerouslySetInnerHTML属性，是用于渲染'<p>xxx</p>'这种字符串，需严格按照此模式来渲染*/}
      <div dangerouslySetInnerHTML={
        { __html: detail?.content }
      }></div>
    </div>
  )
}

export default Detail